<template>
  <div class="map-area-wrapper">
    <div :id="props.id" class="map-area"></div>
  </div>
</template>

<script setup lang="ts">
  import {
    onUnmounted,
    onMounted,
    withDefaults,
    defineProps,
    nextTick,
    defineExpose,
  } from 'vue';
  import { initMapFile } from '@/utils/initMap';

  interface DataItem {
    id: string;
    carNo: string;
    position: number[];
  }
  interface Props {
    id?: string;
    tools: string[];
  }
  const props = withDefaults(defineProps<Props>(), {
    id: 'map-container-add',
    tools: () => {
      return [];
    },
  });

  let map: any = null;
  let initLoading = false;
  let lineArrLocal: DataItem[] = [];
  let makerObjs: any = {};
  let driving: any = null;

  const initMap = () => {
    map = new window.AMap.Map(props.id, {
      resizeEnable: true,
      zoom: 17,
      center: [104.762809, 31.496186],
    });

    driving = new window.AMap.Driving({
      map,
    });
  };

  const setLine = (arr: any[]) => {
    const list = JSON.parse(JSON.stringify(arr)).filter((t) => t.text);

    if (list?.length <= 1) {
      driving.clear();
      return;
    }
    let start;
    let end;
    let waypoints;
    if (list?.length === 2) {
      start = list[0];
      end = list[1];
    } else {
      start = list.splice(0, 1)[0];
      end = list.splice(list.length - 1, 1)[0];
      waypoints = list.map((t) => {
        return new window.AMap.LngLat(t.lng, t.lat);
      });
    }
    driving.search(
      new window.AMap.LngLat(start.lng, start.lat),
      new window.AMap.LngLat(end.lng, end.lat),
      {
        waypoints,
      },
      (status: any) => {
        // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
        if (status === 'complete') {
          map.setCenter([start.lng, start.lat]);
        }
      }
    );
  };

  const initMapLoader = () => {
    return new Promise<void>((resolve, reject) => {
      if (initLoading) {
        resolve();
        return;
      }
      if (!window.AMap) {
        initLoading = true;
        initMapFile()
          .then((res) => {
            initLoading = false;
            window.AMap = res;
            initMap();
            resolve();
          })
          .catch((e) => {
            console.log(e);
            reject(e);
          });
      } else {
        if (!map) {
          initMap();
        }
        resolve();
      }
    });
  };

  const setMarker = (isFitView = false) => {
    const markers = lineArrLocal.map((t) => {
      return {
        carNo: t.carNo,
        icon:
          '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
        position: t.position,
      };
    });

    markers.forEach((marker) => {
      const maherItem = new window.AMap.Marker({
        map,
        icon: marker.icon,
        position: [marker.position[0], marker.position[1]],
        offset: new window.AMap.Pixel(-13, -30),
      });
      maherItem.setLabel({
        direction: 'top',
        offset: new window.AMap.Pixel(10, 0), // 设置文本标注偏移量
        content: `<div class='info'>${marker.carNo}</div>`, // 设置文本标注内容
      });
      makerObjs.push(makerObjs);
    });

    if (isFitView) {
      map.setFitView();
    }
  };

  const setMarkerList = (list: DataItem[], isFitView: boolean) => {
    if (map) {
      map.remove(makerObjs);
      makerObjs = [];
      if (list?.length) {
        lineArrLocal = list;
        setMarker(isFitView);
      }
    }
  };

  defineExpose({
    setMarkerList,
    setLine,
  });

  onMounted(() => {
    nextTick(() => {
      initMapLoader();
    });
  });

  onUnmounted(() => {
    map?.destroy();
  });
</script>

<style lang="less">
  .map-area-wrapper {
    width: 100%;
    height: 100%;
    position: relative;
    .map-area-search {
      position: absolute;
      right: 12px;
      top: 12px;
      z-index: 10;
    }
    .search-pannel {
      position: absolute;
      right: 12px;
      top: 34px;
      height: 300px;
      width: 300px;
      z-index: 10;
      overflow: auto;
    }
    .arco-input-wrapper {
      background: #fff;
    }
  }
  .map-area {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
</style>
